package com.yjps.system.controller;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.yjps.common.authc.PasswordHelper;
import com.yjps.common.message.Message;
import com.yjps.common.page.Pager;
import com.yjps.system.model.Role;
import com.yjps.system.model.User;
import com.yjps.system.service.RoleService;
import com.yjps.system.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;


@Controller
@RequestMapping("/system/user")
public class UserController
{
	private static final Logger log = LoggerFactory.getLogger(UserController.class);


	@Autowired
	UserService userService;
	@Autowired
	RoleService roleService;

	@RequestMapping(value = "/list",method = RequestMethod.GET)
	public String list(Model model,HttpServletRequest request,HttpServletResponse response) throws Exception {
		log.debug("request list all user");
		String type = request.getParameter("type");
		Pager<User> pager = userService.getUserByPager(new Pager<User>(request, response));
        List<User>  users = /*userService.findUserList(type);*/pager.getList();
		for(User u:users){
			Set<Role> roles = u.getRoles();
			StringBuilder sb = new StringBuilder();
			if(roles != null && roles.size()>0){
				for(Role r : roles){
					sb.append(r.getRolename() + ",");
				}
				sb.substring(0, sb.length() - 1);
			}
			u.setViewRoleName(sb.toString());
		}
		log.debug("list all user success");
		model.addAttribute(pager);
//		model.addAttribute("userList",users);
		return "system/user/list";
	}


	@RequestMapping(value = "/edit",method = RequestMethod.GET)
	public String editForm(@RequestParam(value = "id", required = false)String id,Model model){
		if(!StringUtils.isEmpty(id)){
			User user = userService.findUser(Integer.parseInt(id));
			if(user != null){
				log.debug("update user data " + id);
				model.addAttribute("user",user);
			}
		}
		log.debug("request add user");
		List<Role> roles = roleService.roleList();
		model.addAttribute("roles",roles);
		return "system/user/edit";
	}
	@RequestMapping(value = "/edit",method = RequestMethod.POST)
	public String edit(User user,HttpServletRequest request,Model model){
		if(user != null) {
			if (StringUtils.isEmpty(user.getId()) || user.getId()==0/*userService.findUser(user.getId())==null*/) {
				if (userService.findUserByName(user.getUsername()) != null) {
					model.addAttribute("user", user);
					Message message = new Message(false, "the username has exist");
					model.addAttribute("message", message);
					return "system/user/edit";
				}
				user.setIsValid(1);
				System.out.println("user is valid = " + user.getIsValid());
				user.setCreateTime(new Date().toString());
				user.setPassword(PasswordHelper.generatePassword(user.getUsername(), user.getPassword()));
				String[] roles = request.getParameterValues("role");
				System.out.println("roles   " + roles);

				if (roles != null && roles.length != 0) {
					Set<Role> roleSet = new HashSet<>();
//					List<User> userList = new ArrayList<>();
//					userList.add(user);

					for(String r:roles){
						Role role = roleService.findRole(Integer.parseInt(r));
								roleSet.add(role);
//					role.setUsers(userList);

					}
					System.out.println("role.......");
					user.setRoles(roleSet);
					userService.addUser(user);
				}
				log.debug("add  user " + user.getUsername() + "success ");
			}else{
				userService.updateUser(user);
				log.debug("update  user " + user.getUsername() + "success ");
			}
		}
		return "redirect:/system/user/list";
	}

	@RequestMapping(value = "/delete",method = RequestMethod.GET)
	public String delete(@RequestParam(value = "id",required = true)String id){
		log.debug("delete user id " + id);
		userService.deleteUser(Integer.parseInt(id));
		return "redirect:/system/user/list";
	}

	@ResponseBody
	@RequestMapping(value = "/getUser",method = RequestMethod.GET)
	public String getUser(@RequestParam(value = "id",required = true)String id){
		User u = userService.findUser(Integer.parseInt(id));
		List<Role> roles = roleService.roleList();
		u.setAllRoles(roles);
		String jsonString = JSON.toJSONString(u);
		System.out.println("json  = " + jsonString);
		return jsonString;
	}

}
